
import esServerIndexField from "@/stores/esServerIndexField";
import commonAsyncOptions from "@/stores/commonAsyncOptions";
import router from "@/router";
import { removeToken } from "./cookie";
// 创建assets资源路径
function createAssetsUrl(fileName: string): string {
    return new URL(`../assets/${fileName}`, import.meta.url).href;
}

/**
 * 防抖函数
 * @param func 回调函数
 * @param wait 间隔时间
 * @returns 函数
 */
function debounce<F extends FunctionArgs>(fn: F, wait = 0) {
    let timer: NodeJS.Timeout;
    const callback: FunctionArgs = (...args) => {
        timer && clearTimeout(timer);
        timer = setTimeout(() => {
            // @ts-ignore
            fn.apply(this, args);
        }, wait);
    };
    return callback;
}

/**
 * 节流函数
 * @param func 回调函数
 * @param wait 间隔时间
 * @returns 函数
 */
function throttle<F extends FunctionArgs>(fn: F, wait = 0) {
    let timer: NodeJS.Timeout;
    // 利用闭包延长变量声明周期
    const callback: FunctionArgs = (...args) => {
        if (!timer) {
            timer = setTimeout(() => {
                // @ts-ignore
                fn.apply(this, args);
                timer && clearTimeout(timer);
            }, wait);
        }
    };
    return callback;
}
/**
 * 格式化时间
 * @param time 需要格式化的时间
 * @returns 字符串时间
 */
function formatTime<T extends string | number | Date>(time: T) {
    const date = typeof time === "number" ? new Date(time) : new Date(time); // .replace(/-/g, "/")
    const diff = (new Date().getTime() - date.getTime() - 480000) / 1000;
    const dayDiff = Math.floor(diff / 86400);
    const isValidDate = Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date.getTime());
    if (!isValidDate) {
        console.error("不是有效日期格式");
    }
    const formatDate = function (date: Date) {
        const today = new Date(date);
        const year = today.getFullYear();
        const month = today.getMonth() + 1 + "";
        const day = today.getDate() + "";
        const hour = today.getHours() + "";
        const minute = today.getMinutes() + "";
        const second = today.getSeconds() + "";
        return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")} ${hour.padStart(2, "0")}:${minute.padStart(
            2,
            "0"
        )}:${second.padStart(2, "0")}`;
    };
    //小于0或者大于等于31显示原时间
    if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
        if (isNaN(dayDiff)) {
            return formatDate(new Date());
        }
        return formatDate(date);
    }
    return formatDate(date);
}
function formatTime2<T extends string | number | Date>(time: T) {
    const date = typeof time === "number" ? new Date(time) : new Date(time); // .replace(/-/g, "/")
    const diff = (new Date().getTime() - date.getTime() - 480000) / 1000;
    const dayDiff = Math.floor(diff / 86400);
    const isValidDate = Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date.getTime());
    if (!isValidDate) {
        console.error("不是有效日期格式");
    }
    const formatDate = function (date: Date) {
        const today = new Date(date);
        today.setHours(today.getHours() - 8);
        const year = today.getFullYear();
        const month = today.getMonth() + 1 + "";
        const day = today.getDate() + "";
        const hour = today.getHours() + "";
        const minute = today.getMinutes() + "";
        const second = today.getSeconds() + "";
        return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")} ${hour.padStart(2, "0")}:${minute.padStart(
            2,
            "0"
        )}:${second.padStart(2, "0")}`;
    };
    //小于0或者大于等于31显示原时间
    if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
        if (isNaN(dayDiff)) {
            return formatDate(new Date());
        }
        return formatDate(date);
    }
    return formatDate(date);
}

// es处理对象
function esHandleObj<T extends object>(data: T): Array<any> {
    const arr: any = [];
    Object.keys(data).forEach((key: string) => {
        // @ts-ignore
        Object.keys(data[key]).forEach((key2) => {
            if (key2 === "buckets") {
                // @ts-ignore
                const v = data[key][key2];
                if (v.length) {
                    v.forEach((item: { key: string; [key: string]: any }) => {
                        if (item.key) {
                            //判断key是否为空
                            arr.push({
                                index: key,
                                ...item
                            });
                        }
                    });
                }
            }
        });
    });

    return arr;
}
/**
 * 判断一个值是否一个对象
 * @param v
 * @returns boolean
 */
function isObject(v: unknown): v is object {
    return v !== null && typeof v === "object";
}

function backLogin() {
    import("@/stores/main").then(res=>{
        const $store = res.default();
        $store.author = "";
        $store.username = "";
        $store.menuData = [];
        router.replace("/login");
        removeToken();
    })
}

function randomId(len: number = 10): string {
    return Math.random().toString(36).slice(2, len);
}

export function clearCache() {
    const $store1 = esServerIndexField();
    const $store2 = commonAsyncOptions();
    const { esServerIndexMap, esHostAndIndexAndFieldMap } = toRefs($store1);
    for (const key in esServerIndexMap.value) {
        if (Object.prototype.hasOwnProperty.call(esServerIndexMap.value, key)) {
            esServerIndexMap.value[key] = [];
        }
    }
    esHostAndIndexAndFieldMap.value = {};
    const { options } = toRefs($store2);
    // 不需要清除的缓存
    const notClearCache = ["custom_identifier_name", "wyc_name"];
    for (const key in options.value) {
        if (Object.prototype.hasOwnProperty.call(options.value, key) && !notClearCache.includes(key)) {
            // @ts-ignore
            options.value[key] = [];
        }
    }
    setTimeout(() => {
        $store1.getIndexOptions("");
    }, 0);
}
export function toUrl(url: string) {
    if (url.startsWith("http")) {
        return url;
    } else {
        const currentUrl = location.href.split("#")[0];
        return currentUrl + "#" + url;
    }
}

export function getTodayAndYesterdayDate() {
    const date1 = new Date();
    const date2 = new Date();
    date2.setDate(date1.getDate() - 1);
    date1.setHours(0, 0, 0, 0);
    date2.setHours(0, 0, 0, 0);
    return [date2, date1];
}

export function toArticleEsView(host: string, index: string, id: string) {
    window.open(toUrl(`/es-doc?host=${host}&index=${index}&id=${id}`), "_blank");
}
export { createAssetsUrl, throttle, debounce, formatTime, isObject, esHandleObj, backLogin, randomId, formatTime2 };
